import axios from 'axios'
import { MessageBox } from 'mint-ui'
import conf from '@/assets/js/conf'

const DEBUG = conf.debug

axios.defaults.timeout = 60000
axios.defaults.baseURL = conf.baseUrl
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers.put['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.withCredentials = true // 传递session,很重要!很重要!很重要!

let cancel = {}
let promiseArr = {}
const CancelToken = axios.CancelToken


function getQueryParam(key) {
  let match = RegExp('[?&]' + key + '=([^&]*)').exec(window.location.search);  
  return match && match[1].replace(/\+/g, ' ');
}

var token = getQueryParam('token')
console.log(token)
localStorage.setItem("token",token)
// http request 拦截器
/**
 * 拦截请求数据
 */
axios.interceptors.request.use(
  config => {
    if (promiseArr[config.url]) {
      // promiseArr[config.url]('操作取消')
      // promiseArr[config.url] = cancel
    } else {
      promiseArr[config.url] = cancel
    }  
    if (token) {
      config.headers['token'] = token
    }
    
    if (DEBUG) {
      console.log('Request Path: ' + config.method + '  ' + config.url)
      console.log('Request param: ' + JSON.stringify(config.data))
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
/**
 * 拦截响应数据
 */
axios.interceptors.response.use(
  response => {
    if (DEBUG) {
      console.log('Response data: ' + JSON.stringify(response.data))
    }
    checkResponseCode(response.data)
    return response
  },
  error => {
    if (error) {
      console.log('Response Error Data: ' + JSON.stringify(error))
    }
    if (error && error.response && error.response.data) {
      checkResponseCode(error.response.data)
    }
    return Promise.reject(error)
  }
)

function checkResponseCode (data) {
  let code = data.code
  if (!code) {
    return
  }
  let message = null
  switch (code) {
    case '200':
      break
    case '400':
      // message = '请求参数错误，请检查参数'
      break
    case '401':
      message = '登陆失效，请重新登陆'
      MessageBox({
        showClose: true,
        message: message,
        type: 'error',
        duration: 3000
      })
      break
    case '403':
      message = '拒绝访问'
      break
    case '404':
      // message = '请求错误,未找到该资源'
      break
    case '405':
      // message = '请求方法未允许'
      break
    case '408':
      // message = '请求超时'
      break
    case '500':
      // message = '服务器端出错,请联系管理员'
      break
    case '501':
      // message = '网络未实现'
      break
    case '502':
      // message = '网络错误'
      break
    case '503':
      // message = '服务暂时不可用,请联系管理员'
      break
    case '504':
      // message = '网络超时'
      break
    case '505':
      message = 'http版本不支持该请求'
      break
    default:
      message = `操作失败:${data.message}`
      break
  }
  alterMessage(message)
}

function alterMessage (msg) {
  if (msg !== null) {
    MessageBox({
      showClose: true,
      message: msg,
      type: 'error',
      duration: 3000
    })
  }
}

export default {
  get (url, param) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        params: param,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          resolve(err)
        })
    })
  },
  post (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url,
        data: data,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          resolve(err)
        })
    })
  },
  put (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'put',
        url,
        data: data,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          resolve(err)
        })
    })
  },
  delete (url, param) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url,
        cancelToken: new CancelToken(c => {
          cancel = c
        })
      })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          resolve(err)
        })
    })
  },
  request (method, url, data) {
    if (!method || !url) {
      console.log('Method or Url is undefind!')
      return
    }
    method = method.toLowerCase()
    if (method === 'get') {
      return this.get(url, data)
    }
    if (method === 'post') {
      return this.post(url, data)
    }
    if (method === 'delete') {
      return this.delete(url, data)
    }
    if (method === 'put') {
      return this.put(url, data)
    }
  },
  req (path, data) {
    if (!path) {
      console.log('Path is undefind!')
      return
    }
    // TODO 对象或是字符串
    let method = path.method
    let uri = path.uri
    return this.request(method, uri, data)
  },
  async syncReq (url, param) {
    let result = await axios({
      method: 'get',
      url,
      params: param,
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    })
    return result
  }
}
export { token }
